<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>游戏大厅</title>
    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/game_hall.css">
</head>
<body>
    <div class="nav">弈星连珠</div>
    <!-- 整个页面的容器元素-->
    <div class="container">
        <!-- 这个div在container 中处于垂直水平居中的位置的-->
         <div>
            <!--展示用户信息-->
            <div id="screen"></div>

            <!--表示匹配按钮-->
            <div id="match-button">开始匹配</div>
         </div>

    </div>

    <script src="/js/jquery.min.js"></script>

    <script>
        $.ajax({
            type:'get',
            url:'/user/getUserInfo',

            success : function(result){
                let screenDiv = document.querySelector("#screen");
                screenDiv.innerHTML = '玩家：' + result.username + '  积分：' + result.score +
                '<br>' + '比赛场数：'+ result.totalCount + '  获胜场数：' + result.winCount;
            },

            error : function(){
                alert("用户信息获取失败");
            }
        });


        //此处进行初始化websocket,并且实现前端的逻辑
        let websocketUrl = 'ws://'+ location.host +'/findMatch'
        let websocket = new WebSocket(websocketUrl);
        websocket.onopen = function() {
            console.log("onopen");
        }
        websocket.onclose = function() {
            console.log("onclose");
            
        }
        websocket.onerror = function() {
            console.log("onerror")
        }
        //监听页面关闭事件，在页面关闭之前，手动调用这里的websocket的close方法
        window.onbeforeunload = function() {
            websocket.close();
        }

        //处理服务器返回的响应
        websocket.onmessage = function(e){
            //处理服务返回的响应数据

            //返回的数据是一个json字符串，解析为js对象
            let resp = JSON.parse(e.data);
            let matchButton = document.querySelector("#match-button");
             
            if(!resp.ok) {
                console.log("游戏大厅接受到了失败的响应！" +resp.reason);
                alert(resp.reason);
                location.href = "login.html";
                return;
            }

            if (resp.message == 'startMatch'){
                console.log('进入匹配队列成功');
                matchButton.innerHTML = '匹配中...(点击停止)';

            }else if (resp.message == 'stopMatch') {
                console.log('离开匹配队列成功');
                matchButton.innerHTML = '开始匹配';


            }else if (resp.message == 'matchSuccess') {
                console.log('匹配到对手! 进入游戏房间');
                //location.href = "game_room.html";
                location.replace("/game_room.html");  //这个方法浏览器不会留下痕迹

            }else if (resp.message == 'repeatLogin') {
                console.log("已在别处登录");
                alert("已在别处登录")
                //location.href = "login.html";
                location.replace("/login.html");

            } 
            else {
                console.log("接收到了非法响应" + resp.message);
                alert(resp.message);
            }

        }

        //给匹配的按钮添加一个点击时间
        let matchButton = document.querySelector("#match-button");
        matchButton.onclick = function() {
                //在触发websocket请求之前，先确认下websocket连接是否好着呢
                if(websocket.readyState == websocket.OPEN){
                    //如果处在OPEN,说明连接好着的，此时发送的数据有两种可能，开始匹配/停止匹配
                    if(matchButton.innerHTML == '开始匹配'){
                        console.log("开始匹配");
                        websocket.send(JSON.stringify({
                            message: 'startMatch',
                        }));


                    }else if(matchButton.innerHTML == '匹配中...(点击停止)') {
                        console.log("停止匹配");
                        websocket.send(JSON.stringify({
                            message: 'stopMatch',
                        }));
                    }
                }else {
                    alert("当前您的连接已断开，请重新登录");
                    //location.href = "login.html"; 
                    location.replace("/login.html");
                }
        }
 
    </script>


</body>
</html>